import mitt from "mitt";
import html2canvas from "html2canvas";
import JSPDF from "jspdf";

const bus = mitt();

function treeToArray(tree: any[]) {
  let res: any[] = [];
  for (const item of tree) {
    const { children, ...i } = item;
    if (children && children.length) {
      res = res.concat(treeToArray(children));
    }
    res.push(i);
  }
  return res;
}
//时间处理
function convertTimeFormat(str: any) {
  if (!str) {
    return "";
  }
  console.log(str);
  console.log(new Date(str));
  const date = new Date(str);
  const Y = date.getFullYear();
  const M = date.getMonth() + 1;
  const D = date.getDate();
  return Y + "-" + M + "-" + D;
}

/*data:数组
typeId:flag在数组中对应的key
flag:翻译内容
name:返回内容对应的key
*/
function getTranslate(
  data: any[],
  typeId: string,
  flag: string | number,
  name: string,
) {
  return data.some((ele) => ele[typeId] == flag)
    ? data.filter((ele) => ele[typeId] == flag)[0][name]
    : "";
}

type Func = (...args: any[]) => any;

function debounce(
  func: Func,
  delay: number,
  immediate?: boolean,
  resultCallback?: Func,
) {
  let timer: null | ReturnType<typeof setTimeout> = null;
  let isInvoke = false;
  const _debounce = function (this: unknown, ...args: any[]) {
    return new Promise((resolve, reject) => {
      if (timer) clearTimeout(timer);
      if (immediate && !isInvoke) {
        try {
          const result = func.apply(this, args);
          if (resultCallback) resultCallback(result);
          resolve(result);
        } catch (e) {
          reject(e);
        }
        isInvoke = true;
      } else {
        timer = setTimeout(() => {
          try {
            const result = func.apply(this, args);
            if (resultCallback) resultCallback(result);
            resolve(result);
          } catch (e) {
            reject(e);
          }
          isInvoke = false;
          timer = null;
        }, delay);
      }
    });
  };
  _debounce.cancel = function () {
    if (timer) clearTimeout(timer);
    isInvoke = false;
    timer = null;
  };
  return _debounce;
}

const htmlToPDF = async (
  htmlId: string,
  title: string = "报表",
  direction: "l" | "p" = "p", // l 横 | p 竖
) => {
  const node: HTMLElement | any = document.getElementById(
    htmlId,
  ) as HTMLElement;

  const canvas = await html2canvas(node, {
    scale: window.devicePixelRatio * 3,
    useCORS: true,
  });
  const PDF = new JSPDF(direction, "mm", "a4"); // 以mm为单位
  const contentWidth = canvas.width; // 转换成canvas后的宽度
  const contentHeight = canvas.height; // 转换成canvas后的高度

  // 横向
  let imgWidth = contentWidth * (PDF.canvas.height / contentWidth);
  let imgHeight = contentHeight * (PDF.canvas.height / contentWidth);

  // 纵向
  if (direction === "p") {
    imgWidth = contentWidth * (PDF.canvas.height / contentHeight);
    imgHeight = contentHeight * (PDF.canvas.height / contentHeight);
  }

  const pageData = canvas.toDataURL("image/jpeg", 1.0); // 将canvas转成图片
  PDF.addImage(pageData, "JPEG", 0, 0, imgWidth, imgHeight);
  PDF.save(title + ".pdf");
};

function getDuration(second: number) {
  let duration;
  const days = Math.floor(second / 86400);
  const hours = Math.floor((second % 86400) / 3600);
  const minutes = Math.floor(((second % 86400) % 3600) / 60);
  const seconds = Math.floor(((second % 86400) % 3600) % 60);
  // if (days > 0)
  //   duration = days + "天" + hours + "小时" + minutes + "分" + seconds + "秒";
  // else if (hours > 0)
  //   duration = hours + "小时" + minutes + "分" + seconds + "秒";
  // else if (minutes > 0) duration = minutes + "分" + seconds + "秒";
  // else if (seconds > 0) duration = seconds + "秒";
  if (days > 0) duration = days + "天" + hours + "小时" + minutes + "分";
  else if (hours > 0) duration = hours + "小时" + minutes + "分";
  else if (minutes > 0) duration = minutes + "分";
  else if (seconds > 0) duration = seconds + "秒";
  return duration;
}

export {
  treeToArray,
  getTranslate,
  debounce,
  htmlToPDF,
  bus,
  convertTimeFormat,
  getDuration,
};
